import { ResultRes, searchResult, Suggestion } from '@/types/data'
import { SearchAction } from '@/types/store'

/* eslint-disable camelcase */

type State = {
  suggestion: Suggestion
  searchHistory: string[]
  result: searchResult
}
const initialState: State = {
  suggestion: [],
  searchHistory: ['js', 'java', '哈哈'],
  // 存放搜索的结果
  result: { page: 1, per_page: 10, total_count: 0, results: [] }
}

const search = (state = initialState, action: SearchAction): State => {
  if (action.type === 'search/suggestion') {
    return { ...state, suggestion: action.payload }
  } else if (action.type === 'search/history') {
    return {
      ...state,
      searchHistory: action.payload
    }
  } else if (action.type === 'search/clearHistories') {
    return {
      ...state,
      searchHistory: []
    }
  } else if (action.type === 'search/clearItemHistory') {
    return {
      ...state,
      searchHistory: action.payload
    }
  } else if (action.type === 'search/result') {
    let old: ResultRes[] = []
    if (state.result.results) {
      old = state.result.results
    }
    return {
      ...state,
      result: {
        page: action.payload.page,
        per_page: action.payload.per_page,
        total_count: action.payload.total_count,
        results: [...old, ...action.payload.results]
      }
    }
  } else if (action.type === 'search/clearResult') {
    return {
      ...state,
      result: action.payload
    }
  }
  return state
}

export default search
